package org.linphone.sub.utils;

import android.content.Context;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

/**
 * Created by Xiang on 2018/4/3.
 */

public class FileUtil {

	/**
	 * 将数据存到文件中
	 *
	 * @param data 需要保存的数据
	 * @param fileName 文件名
	 */
	public static void saveDataToFile(byte[] data, int startIndex, int length, String fileName)
	{

		File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
		File sdFile = new File(sdCardDir, fileName);
		try
		{
			/**
			 * "fileName"为文件名,MODE_PRIVATE表示如果存在同名文件则覆盖，
			 * 还有一个MODE_APPEND表示如果存在同名文件则会往里面追加内容
			 */
			RandomAccessFile randomFile = new RandomAccessFile(sdFile, "rw");
			long fileLength = randomFile.length();
			// 将写文件指针移到文件尾。
			randomFile.seek(fileLength);
			randomFile.write(data,startIndex,length);
			randomFile.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

	}

	/**
	 * 删除已存储的文件
	 */
	public static void deletefile(String fileName) {
		try {
			// 找到文件所在的路径并删除该文件
			File file = new File(Environment.getExternalStorageDirectory(), fileName);
			file.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从文件中读取数据
	 * @param context context
	 * @param fileName 文件名
	 * @return 从文件中读取的数据
	 */
	private static String loadDataFromFile(Context context, String fileName)
	{
		FileInputStream fileInputStream = null;
		BufferedReader bufferedReader = null;
		StringBuilder stringBuilder = new StringBuilder();
		try
		{
			/**
			 * 注意这里的fileName不要用绝对路径，只需要文件名就可以了，系统会自动到data目录下去加载这个文件
			 */

			fileInputStream = context.openFileInput(fileName);
			bufferedReader = new BufferedReader(
					new InputStreamReader(fileInputStream));
			String result = "";
			while ((result = bufferedReader.readLine()) != null)
			{
				stringBuilder.append(result);
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (bufferedReader != null)
			{
				try
				{
					bufferedReader.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		return stringBuilder.toString();
	}

}
